package dao.reader;

import dao.DaoException;
import model.Reader;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ReaderDaoImpl implements ReaderDao{
    //添加用户
    @Override
    public boolean addReader(Reader reader) throws DaoException {

       String sql = "INSERT INTO reader VALUES(0,?,?,?)";//重要错误点  虽然id设置过了自增，但还是需要指定值的，这样MySQL会自己做处理（否则自己设置要插入的列）
       try(
               Connection conn = getConnection();
               PreparedStatement pstmt = conn.prepareStatement(sql);

               ){
           //pstmt.setInt(1,reader.getId());设置主键自增
           pstmt.setString(1,reader.getName());
           pstmt.setString(2,reader.getPassword());
           pstmt.setString(3, reader.getTelephone());
           pstmt.executeUpdate();
           return true;

       }catch (SQLException e){
           e.printStackTrace();
           return false;
       }



    }

    //按用户名和密码查找该用户名的id
    //如果没有找到返回一个-1  找到返回真实的id
    @Override
    public Reader readerLogin(String name, String password) throws DaoException {
        String sql = "SELECT * FROM reader WHERE name=? and password= ?";
        int id =-1;  //
        try(
                Connection connection = getConnection();
                PreparedStatement pstmt = connection.prepareStatement(sql);
        ){
            pstmt.setString(1,name);
            pstmt.setString(2,password);
            try(ResultSet rst = pstmt.executeQuery()){
                if (rst.next()){
                    //进入这里表示有该用户。

                    Reader reader = new Reader();
                    reader.setId(rst.getInt("id"));
                    reader.setName(name);
                    reader.setTelephone(rst.getString("telephone"));
                    return reader;
                }
            }

        }catch (SQLException e){
            e.printStackTrace();
        }
        return null;
    }
}
